package gw.com.android.upgrade;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import java.io.File;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.presenter.http.Https;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.AppActivities;
import www.com.library.app.Logger;
import www.com.library.view.TintTextView;

/**
 * @author jett
 * @since 2018-11-26.
 */
class UpgradeDialog {

    private final String TAG = "UpgradeHelper";

    private Dialog dialog;
    private boolean force;
    private String url;
    private String comment;

    private View mDownloadView;
    private View app_version_update_view;
    private ProgressBar mProgressBar;
    private TextView mPerView;
    private TextView mCurSizeView;

    UpgradeDialog(boolean force, String url, String comment) {
        this.force = force;
        this.url = url;
        this.comment = comment;
    }

    private Dialog initDialog() {
        Activity activity = AppActivities.getSingleton().currentActivity();
        if (activity == null) {
            Logger.i(TAG, "initDialog activity is null");
            return null;
        }
        Dialog dialog = new Dialog(activity, R.style.dialog_loading_bar_no_frame);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        dialog.setContentView(initView(activity), lp);
        dialog.setCanceledOnTouchOutside(!force);
        dialog.setCancelable(!force);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                RxBus.getInstance().post(GTSConst.REPLY_POP_ADS_AFTER_UGPRADE, 0);
            }
        });
        return dialog;
    }

    private View initView(Context context) {
        View mCustomView = View.inflate(context, R.layout.dialog_upgrade_action, null);
        TextView mBtnPos = mCustomView.findViewById(R.id.app_upgrade_update);
        TextView mBtnNeg = (TintTextView) mCustomView.findViewById(R.id.app_upgrade_cancel);
        mProgressBar = mCustomView.findViewById(R.id.download_progressbar);
        TextView mContentView = mCustomView.findViewById(R.id.tv_content);
        mDownloadView = mCustomView.findViewById(R.id.ll_download);
        mPerView = mCustomView.findViewById(R.id.tv_percentage);
        mCurSizeView = mCustomView.findViewById(R.id.tv_size);
        mContentView.setText(formatComment());
        app_version_update_view = mCustomView.findViewById(R.id.app_version_update_view);

        mBtnPos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startDownload();
            }
        });
        if (force) {
            mBtnNeg.setVisibility(View.GONE);
        } else {
            mBtnNeg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
        return mCustomView;
    }

    private String formatComment() {
        if (TextUtils.isEmpty(comment)) {
            return "";
        }
        String text = Html.fromHtml(comment).toString();
        text = text.replaceAll("[\n+]$", "");
        text = text.replaceAll("\n\n", "\n");
        return text;
    }

    private void onStart() {
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        mDownloadView.setVisibility(View.VISIBLE);
        app_version_update_view.setVisibility(View.GONE);
        mProgressBar.setProgress(0);
    }

    private void startDownload() {
        onStart();
        String fPath = GTConfig.instance().getRootDirectory() + "/" + AppMain.getAppString(R.string.apk_name);
        final File file = new File(fPath);
        inspectLocal(file);
        new Https(url).download(file, new Https.DownloadListener() {
            @Override
            public void onProgress(long progress, long total) {
                mProgressBar.setMax((int) total);
                mProgressBar.setProgress((int) progress);
                int percent = (int) (progress * 100F / total);
                float D = (float) (progress) / 1024 / 1024;
                float T = (float) (total) / 1024 / 1024;
                mPerView.setText(String.valueOf(percent).concat("%"));
                mCurSizeView.setText(AppMain.getApp().getString(R.string.app_upgrade_size, D, T));
                //Logger.i(TAG, "download progress : progress = " + progress + "   total = " + total + "  percent = " + percent);
            }

            @Override
            public void onCompleted() {
                Logger.i(TAG, "download complete");
                if (!force) {
                    dismiss();
                }
                installAPK(file);
            }

            @Override
            public void onFailure(Exception e) {
                Logger.e(TAG, e);
                dismiss();
            }
        });
    }

    private void inspectLocal(File file) {
        File parentFile = file.getParentFile();
        if (parentFile != null) {
            if (!parentFile.exists()) {
                boolean mkdirs = parentFile.mkdirs();
                Logger.i(TAG, "create directory . " + mkdirs);
            }
        }
        if (file.exists()) {
            boolean delete = file.delete();
            Logger.i(TAG, "delete local file first . " + delete);
        }
    }

    /**
     * 开启apk安装界面
     */
    private void installAPK(File file) {
        if (file.exists() && file.length() > 0) {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri uri = FileProvider.getUriForFile(AppMain.getApp(), AppMain.getApp().getPackageName() + ".provider", file);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            }
            Activity mCurActivity = AppActivities.getSingleton().currentActivity();
            if (null != mCurActivity && !mCurActivity.isFinishing()) {
                mCurActivity.startActivity(intent);
            }
        }
    }

    public void show() {
        if (dialog == null) {
            dialog = initDialog();
        }
        if (dialog != null) {
            dialog.show();
        }
    }

    private void dismiss() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

}
